package com.egg.common.redis.util;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import java.util.concurrent.TimeUnit;


/**
 * redis分布式锁帮助类
 * 项目需要配置redis.yml
 *
 * @author east
 */
public class LockUtil {


    private static RedissonClient redissonClient;


    public void setRedissonClient(RedissonClient locker) {
        if (null == locker) {
            return;
        }
        redissonClient = locker;
    }

    /**
     * 尝试获取锁 - 20秒
     *
     * @param lockKey
     * @return
     */
    public static boolean tryLock(String lockKey) {
        return tryLock(lockKey, 0, 20);
    }

    /**
     * 尝试获取锁
     *
     * @param lockKey
     * @param waitTime  最多等待时间
     * @param leaseTime 上锁后自动释放锁时间
     * @return
     */
    public static boolean tryLock(String lockKey, int waitTime, int leaseTime) {
        return tryLock(lockKey, waitTime, leaseTime, TimeUnit.SECONDS);
    }

    /**
     * 尝试获取锁
     *
     * @param lockKey
     * @param waitTime  最多等待时间
     * @param leaseTime 上锁后自动释放锁时间
     * @param unit      时间单位
     * @return
     */
    public static boolean tryLock(String lockKey, int waitTime, int leaseTime, TimeUnit unit) {
        if (null == redissonClient) {
            return false;
        }
        RLock lock = redissonClient.getLock(lockKey);
        try {
            return lock.tryLock(waitTime, leaseTime, unit);
        } catch (InterruptedException e) {
            return false;
        }
    }

    /**
     * 释放锁
     *
     * @param lockKey
     */
    public static void unlock(String lockKey) {
        if (null == redissonClient) {
            return;
        }
        unlock(redissonClient.getLock(lockKey));
    }

    /**
     * 释放锁
     *
     * @param lock
     */
    public static void unlock(RLock lock) {
        if (null == lock) {
            return;
        }
        if (!lock.isLocked()) {
            //未上锁, 跳过
            return;
        }
        if (!lock.isHeldByCurrentThread()) {
            // 非当前执行线程的锁, 跳过
            return;
        }
        // 释放锁
        lock.unlock();
    }
}